package com.wd.tw.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wd.tw.config.AppConfig;
import com.wd.tw.domain.dto.request.ApiRequest;
import com.wd.tw.domain.dto.request.Basic;
import com.wd.tw.domain.dto.request.LoginRequest;
import com.wd.tw.domain.dto.response.ApiResponse;
import com.wd.tw.domain.dto.response.LoginResponse;
import com.wd.tw.utils.HttpUtils;
import com.wd.tw.utils.Md5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;

import static com.wd.tw.constants.ApiConstant.USER_LOGIN;

/**
 * @className: TokenService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/3
 **/

@Service
public class TokenService {

    private String token;
    public static String USER_NAME = "system";
    public static String PASSWORD = "Admin@12345";
    private Long renewalTime;

    @Resource
    AppConfig appConfig;


    @PostConstruct
    public void init() {
        refreshToken();
    }

    // 定时获取 token
    public void refreshToken() {
        System.out.println("刷新token");
        ApiRequest<LoginRequest> loginParam = new ApiRequest<>();
        this.renewalTime=System.currentTimeMillis();

        Basic basic = loginParam.getBasic();
        String pwd = Md5Utils.md5(PASSWORD);

        String rawPwd = basic.getNonce() + "#" +
                basic.getTime() + "#" +
                USER_NAME + "#" + pwd;
        String entryPwd = Md5Utils.md5(rawPwd);

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUser_name(USER_NAME);
        loginRequest.setPassword(entryPwd);
        loginParam.setData(loginRequest);

        String post = HttpUtils.post(appConfig.getBaseApi() + USER_LOGIN, loginParam.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        ApiResponse<LoginResponse> response = null;
        try {
            response = objectMapper.readValue(post, objectMapper.getTypeFactory().constructParametricType(ApiResponse.class, LoginResponse.class));
            this.token = response.getData().getToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取当前 token
    public String getToken() {
        return this.token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Long getRenewalTime() {
        return renewalTime;
    }

    public void setRenewalTime(Long renewalTime) {
        this.renewalTime = renewalTime;
    }

}
